import logging

from django.http import HttpResponseRedirect
from google.appengine.api import users
from google.appengine.ext import db

from GAE.guestbook.models import Account

def auth_required(function):
    '''
    Decorator to handle the authentication
    '''

    def wrap(request, *args, **kwargs):
        '''
        Wrapper function for the function with decorator
        '''

        # Get the user
        user = users.get_current_user()
        
        if user:
            logging.info("Email: %s" % user.email())
            logging.info("Nick Name: %s" % user.nickname())

            query = db.GqlQuery("SELECT * FROM Account where login= :1",user)

            if not query.get():
                account = Account()
                account.login = user
                account.primary_email = user.email()

                logging.info("Trying to create a user, %s" % user.nickname())
                account.put()

            return function(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(users.create_login_url(request.path))


    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__

    return wrap